import { createBrowserRouter, RouterProvider } from "react-router-dom";
import routerForm from "./router";
import { Suspense, useEffect, useState } from "react";
import { generatesRoutes } from "./utils/generatesRoutes";
import { useDispatch, useSelector } from "react-redux";
import { getMenuList } from "./api/users";
import { setMenu } from "./store/login/authSlice";
import { type Router } from "@remix-run/router";

function App() {
  const { token } = useSelector((state: any) => state.authSlice);
  const [routes, setRoutes] = useState<any>(null);
  const dispatch = useDispatch();

  useEffect(() => {
    async function getItem() {
      let router: Router;
      const { data } = await getMenuList();
      if (data.length) {
        dispatch(setMenu(data));
        const routers = generatesRoutes(data);
        const routes = [...routerForm];
        routes[0].children = routers;
        routes[0].children[0].index = true;
        router = createBrowserRouter(routes);
      } else {
        router = createBrowserRouter(routerForm);
      }
      setRoutes(router);
    }

    getItem();
  }, [token, dispatch]);

  if (routes) {
    return (
      <>
        <Suspense fallback={<div>正在加载中...</div>}>
          <RouterProvider router={routes}></RouterProvider>
        </Suspense>
      </>
    );
  } else {
    return (
      <>
        <div>正在施工ing</div>
      </>
    );
  }
}

export default App;
